<template>
  <div class="app-container">

    <avue-crud
      :option="option"
      :data="data"
      :table-loading="loading"
      :page.sync="page"
      :permission="permission"
      @on-load="onLoad"
      @row-save="rowSave"
      @current-change="currentChange"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="resetChange"
    >

      <template slot="menuLeft">
        <div style="display:inline-block;">
          <div style="display:flex">
            <el-button
              type="primary"
              size="small"
              @click="addFromSour"
              icon="el-icon-plus"
              v-has="'purposeAdd'"
            >
              新 增
            </el-button>
            <el-upload
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="onSuccess"
              :on-error="onError"
              :headers="headers"
              :action="importCustomer"
              v-has="'purposeImport'"
            >
              <el-button
                type="primary"
                size="small"
                :icon="importDataBtnIcon"
              >
                {{importDataBtnText}}
              </el-button>
            </el-upload>
            <el-button
              size="small"
              type="primary"
              @click="downloadTemp"
              icon="el-icon-download"
              v-has="'purposeModelDownLoad'"
            >
              模板下载
            </el-button>
          </div>
        </div>
      </template>

      <template
        slot="menu"
        slot-scope="scope"
      >
        <el-button
          size="small"
          type="text"
          @click="checkOpen(scope.row)"
          icon="el-icon-view"
        >查看</el-button>
        <el-button
          size="small"
          type="text"
          @click="rowDel(scope.row)"
          icon="el-icon-delete"
          v-has="'purposeDelete'"
        >删除</el-button>
      </template>

      <!--            <template slot="icon" slot-scope="scope">-->
      <!--                <div v-if="scope.row.icon">-->
      <!--                    <svg-icon :icon-class="scope.row.icon"></svg-icon>-->
      <!--                </div>-->
      <!--            </template>-->
    </avue-crud>

    <company
      :openDialog="openDialog"
      :title="title"
      :qylxList="qylxList"
      ref="company"
      @save="save"
      @handleReset="handleReset"
    />

    <el-dialog
      title="导入结果"
      :visible.sync="imptRestDialogVisible"
      width="45%"
    >
      <p
        v-for="o in imptRestInfo"
        :key="o"
        class=" text item"
        style="text-indent:30px"
      >
        {{ o }}
      </p>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="closeRestDialog"
        >关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 查看 -->
    <el-dialog
      title="查看"
      :visible.sync="checkDialog"
      width="60%"
      center
    >
      <el-form
        ref="form"
        :model="dataList"
        label-width="100px"
      >
        <div class="message">
          <div class="module">
            <el-tabs v-model="active">
              <el-tab-pane
                label="企业信息"
                name="first"
              >
                <table class="detailtable">
                  <tr>
                    <td width="15%">企业名称</td>
                    <td width="35%">{{dataList.qymc}}</td>
                    <td width="15%">统一社会信用代码</td>
                    <td width="35%">{{dataList.shtyxydm}}</td>
                  </tr>
                  <tr>
                    <td width="15%">法人姓名</td>
                    <td width="35%">{{dataList.fddbr}}</td>
                    <td width="15%">联系方式</td>
                    <td width="35%">{{dataList.dh}}</td>
                  </tr>
                  <tr>
                    <td width="15%">注册时间</td>
                    <td width="35%">{{dataList.clrq}}</td>
                    <td width="15%">注册资金</td>
                    <td width="35%">{{dataList.zczb}}万元</td>
                  </tr>
                  <tr>
                    <td width="15%">所属行业</td>
                    <td width="35%">{{dataList.sshy}}</td>
                    <td width="15%">所属区域</td>
                    <td width="35%">{{dataList.ssqu}}</td>
                  </tr>
                  <tr>
                    <td width="15%">企业类型</td>
                    <td colspan="3">{{dataList.qylx | filterQylx(qylxList)}}</td>
                  </tr>
                  <tr>
                    <td width="15%">注册地址</td>
                    <td colspan="3">{{dataList.zs}}</td>
                  </tr>
                </table>
              </el-tab-pane>
            </el-tabs>
          </div>
          <!--                    <div class="module">-->
          <!--                        <el-tabs v-model="active">-->
          <!--                            <el-tab-pane label="法人信息" name="first">-->
          <!--                                <table class="detailtable">-->
          <!--                                    <tr>-->
          <!--                                        <td width="15%">姓名</td>-->
          <!--                                        <td>{{dataList.fddbr}}</td>-->
          <!--                                        <td width="15%">性别</td>-->
          <!--                                        <td>{{dataList.xb}}</td>-->
          <!--                                        <td width="15%">出生日期</td>-->
          <!--                                        <td>{{dataList.csrq}}</td>-->
          <!--                                    </tr>-->
          <!--                                    <tr>-->
          <!--                                        <td width="15%">籍贯</td>-->
          <!--                                        <td>{{dataList.jg}}</td>-->
          <!--                                        <td width="15%">婚姻状况</td>-->
          <!--                                        <td>{{dataList.hyzk}}</td>-->
          <!--                                        <td width="15%">学历</td>-->
          <!--                                        <td>{{dataList.xl}}</td>-->
          <!--                                    </tr>-->
          <!--                                    <tr>-->
          <!--                                        <td width="15%">身份证号</td>-->
          <!--                                        <td>{{dataList.sfzjhm}}</td>-->
          <!--                                        <td width="15%">联系方式</td>-->
          <!--                                        <td>{{dataList.lxdh}}</td>-->
          <!--                                        <td width="15%">邮箱</td>-->
          <!--                                        <td>{{dataList.yx}}</td>-->
          <!--                                    </tr>-->
          <!--                                    <tr>-->
          <!--                                        <td width="15%">联系地址</td>-->
          <!--                                        <td colspan="5">{{dataList.zs}}</td>-->
          <!--                                    </tr>-->
          <!--                                </table>-->
          <!--                            </el-tab-pane>-->
          <!--                        </el-tabs>-->
          <!--                    </div>-->
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  add,
  getC,
  delC,
  addToPurpose,
  // expCtmp,
  upC,
} from '@/api/manager.js'
import company from './company'
import store from '@/store'
import { getField } from '@/api/user.js'
export default {
  components: {
    company,
  },
  data() {
    return {
      loading: false,
      form: {},
      permission: {},
      importCustomer: '',
      downCustomerTmp: '',
      /* 企业类型 */
      title: '新增意向客户',
      qylxList: [],
      /* 角色控制：TODO*/
      managerRole: true,

      checkDialog: false,
      dataList: {},
      active: 'first',
      searchList: {},
      /* 分页 */
      page: {
        pageSize: 10,
        pageSizes: [10, 20, 30, 40, 50, 100],
        pagerCount: 5,
        currentPage: 1,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        background: false,
      },
      // 显示窗口
      openDialog: false,
      imptRestDialogVisible: false,
      imptRestInfo: [],
      data: [
        {
          id: 1,
          deptValue: '机构1',
          orgCode: '编号',
          deptPid: '上级机构',
          oindex: 1,
          icon: 'back',
          note: '信息描述',
        },
      ],
      // clearBtnVisible:false,
      // clearBtn:true,
      importDataBtnText: '导 入',
      importDataBtnIcon: 'el-icon-upload2',
      importDataDisabled: false,
      option: {
        headerAlign: 'center',
        align: 'center',
        border: true,
        // index: true,
        // indexLabel: '序号',
        columnBtn: false,
        refreshBtn: false,
        selectClearBtn: false,
        searchBtn: true,
        searchLabelWidth: '20%',
        searchSpan: 8,
        searchMenuSpan: 4,
        searchShowBtn: false,
        indexWidth: 100,
        card: true,
        // defaultExpandAll: true,
        dialogDrag: false,
        viewBtn: false,
        delBtn: false,
        excelBtn: false,
        selection: true,
        editBtn: false,
        // align:center,

        // searchLabelWidth: 150,
        column: [
          {
            label: '企业名称',
            prop: 'qymc',
            display: false,
            align: 'center',
            search: true,
          },
          {
            label: '统一社会信用代码',
            prop: 'shtyxydm',
            display: false,
            align: 'center',
            search: true,
          },
          {
            label: '企业类型',
            prop: 'qylx',
            display: false,
            search: true,
            align: 'center',
            type: 'select',
            dicData: [
              {
                label: '小微企业',
                value: '1',
              },
              {
                label: '中型企业',
                value: '2',
              },
              {
                label: '大型企业',
                value: '3',
              },
              {
                label: '超大型企业',
                value: '4',
              },
              {
                label: '个体工商户',
                value: '5',
              },
            ],
          },
          {
            label: '法人姓名',
            prop: 'fddbr',
            search: true,
            // searchLabelWidth: 155,
            align: 'center',
            display: false,
          },
          {
            label: '注册地址',
            prop: 'zs',
            display: false,
            hide: true,
          },
          {
            label: '企业综合评分',
            prop: 'score',
            display: false,
          },
          {
            label: '联系方式',
            prop: 'lxdh',
            display: false,
          },
          {
            label: '创建时间',
            prop: 'createTime',
            display: false,
          },
        ],

        group: [
          {
            icon: 'el-icon-info',
            label: '企业信息',
            collapse: true,
            // searchbtn: true,
            column: [
              {
                label: '企业名称',
                // rules: [{
                //    required: true,
                //    message: "请输入企业名称",
                //    trigger: "blur"
                // }],
                prop: 'qymc',
              },
              {
                label: '统一社会信用代码',
                prop: 'shtyxydm',
                labelWidth: 145,
              },
              {
                label: '注册时间',
                prop: 'clrq',
                type: 'date',
              },
              {
                label: '注册资金',
                prop: 'zczb',
              },
              {
                label: '所属行业',
                prop: 'sshy',
                type: 'select',
                dicData: [
                  {
                    label: '请选择',
                    value: '',
                  },
                  {
                    label: '农林牧渔业',
                    value: '0',
                  },
                  {
                    label: '教育',
                    value: '1',
                  },
                  {
                    label: '采矿业',
                    value: '2',
                  },
                ],
              },

              {
                label: '所属区域',
                prop: 'ssqu',
                type: 'select',
                dicData: [
                  {
                    label: '请选择',
                    value: '',
                  },
                  {
                    label: '崇川区',
                    value: '226001',
                  },
                  {
                    label: '通州区',
                    value: '226300',
                  },
                  {
                    label: '海门区',
                    value: '226100',
                  },
                  {
                    label: '启东市',
                    value: '226001',
                  },
                  {
                    label: '如皋市',
                    value: '226500',
                  },
                  {
                    label: '海安市',
                    value: '226600',
                  },
                  {
                    label: '如东县',
                    value: '226400',
                  },
                ],
              },
              {
                label: '企业类型',
                prop: 'qylx',
              },
              {
                label: '联系方式',
                prop: 'dh',
              },
              {
                label: '注册地址',
                prop: 'zs',
              },
              // {
              //     label: '企业性质',
              //     prop: 'qyxz',
              // }
            ],
          },
          {
            icon: 'el-icon-info',
            label: '法人信息',
            collapse: true,
            column: [
              {
                label: '法人姓名',
                prop: 'fddbr',
              },
              {
                label: '性别',
                prop: 'xb',
                type: 'select',
                dicData: [
                  {
                    label: '男',
                    value: '1',
                  },
                  {
                    label: '女',
                    value: '0',
                  },
                ],
              },
              {
                label: '出生日期',
                type: 'csrq',
                prop: 'birthday',
              },
              {
                label: '籍贯',
                prop: 'jg',
              },
              {
                label: '婚姻状况',
                prop: 'hyzk',
                type: 'select',
                dicData: [
                  {
                    label: '已婚',
                    value: '1',
                  },
                  {
                    label: '未婚',
                    value: '0',
                  },
                ],
              },
              {
                label: '学历',
                prop: 'xl',
                type: 'select',
                dicData: [
                  {
                    label: '请选择',
                    value: '',
                  },
                  {
                    label: '专科',
                    value: '0',
                  },
                  {
                    label: '本科',
                    value: '1',
                  },
                  {
                    label: '其他',
                    value: '2',
                  },
                ],
              },

              {
                label: '身份证',
                prop: 'sfzjhm',
              },
              {
                label: '手机号',
                prop: 'lxdh',
              },
              {
                label: '邮箱',
                prop: 'yx',
              },
              {
                label: '联系地址',
                prop: 'dz',
              },
            ],
          },
        ],
      },
    }
  },

  computed: {
    headers() {
      return {
        TOKEN: this.$store.getters.token,
      }
    },
  },
  created() {
    var buttonpermsStr = JSON.parse(localStorage.getItem('btnList'))
    this.option.excelBtn =
      buttonpermsStr.indexOf('purposeExport') > -1 ? true : false
    let params = {
      page: 1,
      size: 100,
      code: 'QYLX',
    }
    getField(params).then((res) => {
      if (res.status) {
        this.qylxList = res.data.records
      }
    })
  },
  filters: {
    filterQylx(val, qylxList) {
      var isnum = /^\d+$/.test(val)
      if (isnum) {
        return qylxList.filter((item) => item.fieldCode == val)[0].fieldName
      } else {
        return val
      }
    },
  },
  methods: {
    onLoad(page, params = {}) {
      // 上传文件的url
      let baseUrl2 = process.env.VUE_APP_BASE_API
      this.importCustomer = baseUrl2 + '/customer/purpose/import'

      this.downCustomerTmp = baseUrl2 + '/customer/purpose/downloadTemp'

      // 根据不同的角色 控制按钮显示
      // 管理人员角色
      if (this.managerRole === true) {
        this.permission = {
          // 组件自带新增按钮不显示
          addBtn: false,
        }
        // 导入按钮显示
        this.importDataDisabled = false

        // 普通人员角色
      } else {
        this.permission = {
          // 组件自带新增按钮不显示
          addBtn: false,
        }
        // 导入按钮不显示
        this.importDataDisabled = true
      }

      let searchList = this.searchList
      Object.assign(params, {
        ...searchList,
        pageNum: this.page.currentPage,
        pageSize: this.page.pageSize,
      })

      /* if (page.layout) {
                    Object.assign(params, {
                        page: 1,
                        size: 10,
                    });
                } else {
                    Object.assign(params, page);
                } */

      this.loading = true
      getC(params).then((data) => {
        if (data.status) {
          this.loading = false
          this.data = data.data.records
          this.page.total = data.data.total
        }
      })
    },
    /* 清空 */
    resetChange() {
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.searchList = {}
      this.onLoad()
    },
    /* 搜索筛选 */
    searchChange(params, done) {
      done()
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.searchList = {
        ...params,
      }
      this.onLoad()
    },

    downloadTemp() {
      document.location.href = this.downCustomerTmp
    },

    exportForm() {
      // this.exportLoading = true
      this.expCtmp(this.listQuery).then((res) => {
        // //listQuery是当前传参数组
        // const link = document.createElement('a')
        // const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        // link.style.display = 'none'
        // link.href = URL.createObjectURL(blob)
        // let num = ''
        // for (let i = 0; i < 10; i++) {
        //     num += Math.ceil(Math.random() * 10)
        // }
        // link.setAttribute('download', '意向客户模板_' + num + '.xls')
        // document.body.appendChild(link)
        // link.click()
        // // this.exportLoading = false
        // document.body.removeChild(link)

        this.$notify({
          type: 'success',
          title: '导出成功',
          message: h('p', null, [
            h(
              'i',
              {
                style: 'color: red',
              },
              'Go+订单.xlsx'
            ),
            h('span', null, ' 成功导出到'),
            h(
              'i',
              {
                style: 'color: teal',
              },
              res.data
            ),
          ]),
        })
      })
    },
    expCtmp(data) {
      let url = process.env.VUE_APP_BASE_API + '/customer/purpose/downloadTemp'
      // return request({
      //     url: url,
      //     method: 'get',
      //     params: data,
      //     responseType: 'blob' //!!!导出时必填
      // })
      //

      return this.$axios.get(url, {
        method: 'get',
        params: data,
        responseType: 'blob',
      })
    },

    closeRestDialog() {
      this.imptRestDialogVisible = false
      this.onLoad(this.page)
    },
    onError(err, file, fileList) {
      this.importDataBtnText = '导 入'
      this.importDataBtnIcon = 'el-icon-upload2'
      this.importDataDisabled = false
    },
    onSuccess(response, file, fileList) {
      this.importDataBtnText = '导 入'
      this.importDataBtnIcon = 'el-icon-upload2'
      this.importDataDisabled = false

      this.imptRestDialogVisible = true
      if (response.status) {
        this.imptRestInfo = response.data
      } else {
        this.imptRestInfo.push(response.msg)
      }
    },
    beforeUpload(file) {
      var FileExt = file.name.replace(/.+\./, '')
      if (['xlsx'].indexOf(FileExt.toLowerCase()) === -1) {
        this.$message({
          type: 'warning',
          message: '请使用下载的模板，上传后缀名为xlsx的文件！',
        })
        return false
      }

      this.importDataBtnText = '正在导入'
      this.importDataBtnIcon = 'el-icon-loading'
      this.importDataDisabled = true
      this.imptRestInfo = []
    },

    submitUpload() {
      // var aa = store.state.token;
      // aa = store.getters.token;
      // aa = store.getters.access_token;
      // aa = this.$store.getters;
      // debugger
      this.$refs.upload.submit()
    },

    /* 新增 */
    rowSave(row, done, loading) {
      add(row).then(
        (data) => {
          if (data.status) {
            this.onLoad(this.page)
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
            done()
          } else {
            this.$message.error(data.msg)
            loading()
          }
        },
        (error) => {
          window.console.log(error)
          loading()
        }
      )
    },

    addFromSour() {
      // 显示窗口
      this.openDialog = true
      /* this.$nextTick(() => {
                        this.$refs.company.init();
                    }); */
      // this.company.init();
    },
    //新增取消
    handleReset(val) {
      this.openDialog = val
    },
    save(params) {
      addToPurpose(params).then(
        (data) => {
          if (data.status) {
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
            this.openDialog = false
            this.$refs.company.resetForm()
            this.onLoad(this.page)
          } else {
            this.$message.error(data.msg)
          }
        },
        (error) => {
          window.console.log(error)
        }
      )
    },
    /* 查看 */
    checkOpen(row) {
      this.checkDialog = true
      this.dataList = { ...row }
    },

    /* 修改 */
    rowUpdate(row, index, done, loading) {
      // delete row.createTime;
      // delete row.updateTime;
      upC(row).then(
        (data) => {
          if (data.status) {
            this.onLoad(this.page)
            this.$message({
              type: 'success',
              message: '修改成功!',
            })
            done()
          } else {
            this.$message.error(data.msg)
            loading()
          }
        },
        (error) => {
          window.console.log(error)
          loading()
        }
      )
    },
    /* 改变页码 */
    currentChange(currentPage) {
      this.page.currentPage = currentPage
    },
    /* 删除 */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delC({
          shtyxydm: row.shtyxydm,
        }).then((res) => {
          this.onLoad(this.page)
          if (res.status) {
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
          } else {
            this.$message({
              type: 'error',
              message: res.msg,
            })
          }
        })
      })
    },
  },
}
</script>

<style scoped="scoped" lang="scss">
/deep/ .avue-crud__pagination {
  text-align: center;
}
.detailtable {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 0;
  border: #e5e5e5 solid 1px;
}
.detailtable tr {
  width: 100%;
}
.detailtable td {
  padding: 8px 10px;
  text-align: left;
  line-height: 24px;
  font-size: 14px;
  color: #434343;
  border: #e5e5e5 solid 1px;
}
.detailtable td {
  font-weight: normal;
  background-color: #fff;
}
.detailtable td {
  word-break: break-all;
}
</style>